/**
 * 销售机会详情页面交互逻辑
 * 实现完整的机会跟踪和管理功能
 */

class OpportunityDetail {
    constructor() {
        this.opportunityId = this.getOpportunityIdFromUrl();
        this.currentOpportunity = null;
        this.followupHistory = [];
        
        this.init();
    }

    init() {
        this.loadOpportunityData();
        this.bindEvents();
        this.initializeComponents();
    }

    getOpportunityIdFromUrl() {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get('id') || '1'; // 默认ID为1用于演示
    }

    bindEvents() {
        // 页面操作按钮
        this.bindHeaderActions();
        
        // 跟进记录相关
        this.bindFollowupEvents();
        
        // 快捷操作
        this.bindQuickActions();
        
        // 阶段推进
        this.bindStageActions();
        
        // 模态框事件
        this.bindModalEvents();
    }

    // ==================== 页面头部操作 ====================
    bindHeaderActions() {
        // 编辑机会
        document.getElementById('edit-opportunity-btn')?.addEventListener('click', () => {
            this.editOpportunity();
        });
        
        // 推进阶段
        document.getElementById('advance-stage-btn')?.addEventListener('click', () => {
            this.showAdvanceStageModal();
        });
    }

    editOpportunity() {
        window.location.href = `opportunity-form.html?id=${this.opportunityId}`;
    }

    showAdvanceStageModal() {
        // 显示阶段推进模态框
        console.log('Showing advance stage modal...');
        this.showNotification('阶段推进功能开发中...', 'info');
    }

    // ==================== 跟进记录管理 ====================
    bindFollowupEvents() {
        // 添加跟进记录
        document.getElementById('add-followup-btn')?.addEventListener('click', () => {
            this.showAddFollowupModal();
        });
        
        // 跟进记录操作按钮
        this.bindFollowupActions();
    }

    bindFollowupActions() {
        // 使用事件委托处理跟进记录的编辑和删除
        document.addEventListener('click', (e) => {
            if (e.target.closest('.followup-actions')) {
                const action = e.target.closest('.action-btn');
                if (action) {
                    const followupId = action.closest('.followup-item').dataset.followupId;
                    
                    if (action.querySelector('.fa-edit')) {
                        this.editFollowup(followupId);
                    } else if (action.querySelector('.fa-trash')) {
                        this.deleteFollowup(followupId);
                    }
                }
            }
        });
    }

    showAddFollowupModal() {
        const modal = document.getElementById('add-followup-modal');
        if (modal) {
            // 重置表单
            this.resetFollowupForm();
            
            // 设置默认时间为当前时间
            const now = new Date();
            const currentTime = now.toISOString().slice(0, 16);
            document.getElementById('followup-time').value = currentTime;
            
            modal.style.display = 'flex';
            setTimeout(() => modal.classList.add('show'), 10);
        }
    }

    resetFollowupForm() {
        const form = document.querySelector('#add-followup-modal form') || 
                     document.getElementById('add-followup-modal');
        
        const inputs = form.querySelectorAll('input, select, textarea');
        inputs.forEach(input => {
            if (input.type === 'checkbox' || input.type === 'radio') {
                input.checked = false;
            } else {
                input.value = '';
            }
        });
    }

    closeFollowupModal() {
        const modal = document.getElementById('add-followup-modal');
        if (modal) {
            modal.classList.remove('show');
            setTimeout(() => modal.style.display = 'none', 300);
        }
    }

    saveFollowup() {
        // 收集表单数据
        const followupData = this.collectFollowupData();
        
        // 验证数据
        if (!this.validateFollowupData(followupData)) {
            return;
        }
        
        // 保存跟进记录（实际项目中调用API）
        this.submitFollowupData(followupData);
    }

    collectFollowupData() {
        return {
            time: document.getElementById('followup-time')?.value,
            method: document.getElementById('followup-method')?.value,
            duration: document.getElementById('followup-duration')?.value,
            topic: document.getElementById('followup-topic')?.value,
            content: document.getElementById('followup-content')?.value,
            customerFeedback: document.getElementById('customer-feedback')?.value,
            effect: document.getElementById('communication-effect')?.value,
            intentionChange: document.getElementById('intention-change')?.value,
            stageProgress: document.getElementById('stage-progress')?.value,
            nextFollowupTime: document.getElementById('next-followup-time')?.value,
            nextFollowupMethod: document.getElementById('next-followup-method')?.value,
            nextFollowupGoal: document.getElementById('next-followup-goal')?.value
        };
    }

    validateFollowupData(data) {
        if (!data.time) {
            this.showNotification('请选择跟进时间', 'error');
            return false;
        }
        if (!data.method) {
            this.showNotification('请选择跟进方式', 'error');
            return false;
        }
        if (!data.topic) {
            this.showNotification('请填写沟通主题', 'error');
            return false;
        }
        if (!data.content) {
            this.showNotification('请填写详细内容', 'error');
            return false;
        }
        if (!data.customerFeedback) {
            this.showNotification('请填写客户反馈', 'error');
            return false;
        }
        if (!data.effect) {
            this.showNotification('请选择沟通效果', 'error');
            return false;
        }
        if (!data.intentionChange) {
            this.showNotification('请选择意向变化', 'error');
            return false;
        }
        
        return true;
    }

    submitFollowupData(data) {
        // 模拟API调用
        console.log('Submitting followup data:', data);
        
        // 显示加载状态
        this.showNotification('正在保存跟进记录...', 'info');
        
        // 模拟异步保存
        setTimeout(() => {
            this.closeFollowupModal();
            this.showNotification('跟进记录已保存', 'success');
            
            // 重新加载跟进记录
            this.loadFollowupHistory();
            
            // 如果设置了下次跟进，更新下次跟进卡片
            if (data.nextFollowupTime) {
                this.updateNextFollowupCard(data);
            }
        }, 1000);
    }

    editFollowup(followupId) {
        console.log(`Editing followup ${followupId}`);
        this.showNotification('编辑功能开发中...', 'info');
    }

    deleteFollowup(followupId) {
        if (confirm('确定要删除这条跟进记录吗？')) {
            console.log(`Deleting followup ${followupId}`);
            this.showNotification('跟进记录已删除', 'success');
            this.loadFollowupHistory();
        }
    }

    // ==================== 快捷操作 ====================
    bindQuickActions() {
        const quickActions = document.querySelectorAll('.action-button');
        
        quickActions.forEach(button => {
            button.addEventListener('click', (e) => {
                const action = this.getActionFromButton(e.target);
                this.executeQuickAction(action);
            });
        });
    }

    getActionFromButton(button) {
        const icon = button.querySelector('i');
        if (icon?.classList.contains('fa-phone')) return 'call';
        if (icon?.classList.contains('fa-comment')) return 'wechat';
        if (icon?.classList.contains('fa-file-alt')) return 'proposal';
        if (icon?.classList.contains('fa-calendar-plus')) return 'schedule';
        if (icon?.classList.contains('fa-exchange-alt')) return 'transfer';
        if (icon?.classList.contains('fa-times-circle')) return 'close';
        return 'unknown';
    }

    executeQuickAction(action) {
        switch (action) {
            case 'call':
                this.makeCall();
                break;
            case 'wechat':
                this.sendWechat();
                break;
            case 'proposal':
                this.sendProposal();
                break;
            case 'schedule':
                this.scheduleFollowup();
                break;
            case 'transfer':
                this.transferOpportunity();
                break;
            case 'close':
                this.closeOpportunity();
                break;
            default:
                this.showNotification('未知操作', 'error');
        }
    }

    makeCall() {
        const phone = this.currentOpportunity?.customerPhone || '139****8002';
        this.showNotification(`正在拨打电话 ${phone}...`, 'info');
        
        // 实际项目中可能会集成电话系统
        // 这里模拟添加通话记录
        setTimeout(() => {
            this.showAddFollowupModal();
            // 预填通话相关信息
            document.getElementById('followup-method').value = 'phone';
            document.getElementById('followup-topic').value = '电话沟通';
        }, 500);
    }

    sendWechat() {
        this.showNotification('正在打开微信...', 'info');
        // 实际项目中可能会打开微信小程序或网页版
    }

    sendProposal() {
        this.showNotification('正在准备方案...', 'info');
        // 实际项目中跳转到方案管理页面
    }

    scheduleFollowup() {
        this.showAddFollowupModal();
        // 预填下次跟进信息
        const tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate() + 1);
        tomorrow.setHours(10, 0, 0, 0);
        
        document.getElementById('next-followup-time').value = 
            tomorrow.toISOString().slice(0, 16);
    }

    transferOpportunity() {
        if (confirm('确定要转移这个销售机会吗？')) {
            this.showNotification('转移功能开发中...', 'info');
        }
    }

    closeOpportunity() {
        if (confirm('确定要关闭这个销售机会吗？此操作不可撤销。')) {
            this.showNotification('正在关闭机会...', 'info');
            setTimeout(() => {
                this.showNotification('销售机会已关闭', 'success');
                // 实际项目中可能会跳转到列表页
            }, 1000);
        }
    }

    // ==================== 阶段推进 ====================
    bindStageActions() {
        // 阶段时间线点击
        document.addEventListener('click', (e) => {
            if (e.target.closest('.timeline-stage')) {
                const stage = e.target.closest('.timeline-stage');
                if (stage.classList.contains('completed') || stage.classList.contains('current')) {
                    this.showStageDetails(stage);
                }
            }
        });
    }

    showStageDetails(stageElement) {
        const stageNumber = stageElement.querySelector('.stage-dot').textContent;
        const stageName = stageElement.querySelector('.stage-title').textContent;
        
        this.showNotification(`查看${stageName}阶段详情...`, 'info');
        // 实际项目中可能会显示阶段详情模态框
    }

    // ==================== 模态框管理 ====================
    bindModalEvents() {
        // 跟进记录模态框
        const followupModal = document.getElementById('add-followup-modal');
        
        // 点击遮罩关闭
        followupModal?.addEventListener('click', (e) => {
            if (e.target === followupModal) {
                this.closeFollowupModal();
            }
        });
        
        // ESC键关闭
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                this.closeFollowupModal();
            }
        });
    }

    // ==================== 数据加载 ====================
    loadOpportunityData() {
        // 模拟API请求加载机会数据
        setTimeout(() => {
            this.currentOpportunity = this.getMockOpportunityData();
            this.updateOpportunityDisplay();
            this.loadFollowupHistory();
        }, 300);
    }

    getMockOpportunityData() {
        return {
            id: this.opportunityId,
            number: 'OPP20250121001',
            name: '李女士夫妇-云南深度7日游',
            level: 'A',
            levelText: 'A级 (热门)',
            levelDesc: '意向强烈，预计7天内成交',
            currentStage: 5,
            currentStageName: '决策促成',
            progress: 83,
            expectedAmount: 15800,
            expectedCloseDate: '2025-01-25',
            expectedDepartureDate: '2025-02-10',
            customer: {
                id: 101,
                name: '李大妈',
                phone: '139****8002',
                age: 65,
                health: '健康良好',
                purchaseCount: 2
            },
            consultant: {
                id: 1,
                name: '张顾问',
                role: '高级旅游顾问',
                phone: '138****0001',
                monthlyDeals: 12,
                conversionRate: 68
            },
            source: '邀约活动转化',
            type: '老客户复购',
            peopleCount: 2,
            budget: '15,000-20,000元',
            createdAt: '2025-01-18 14:30'
        };
    }

    updateOpportunityDisplay() {
        if (!this.currentOpportunity) return;
        
        // 更新页面标题
        document.querySelector('.page-title').textContent = this.currentOpportunity.name;
        
        // 更新概览卡片
        this.updateOverviewCards();
        
        // 更新侧边栏信息
        this.updateSidebarInfo();
    }

    updateOverviewCards() {
        const opp = this.currentOpportunity;
        
        // 更新机会等级卡片
        document.querySelector('.level-card .card-value').textContent = opp.levelText;
        document.querySelector('.level-card .card-desc').textContent = opp.levelDesc;
        
        // 更新当前阶段卡片
        document.querySelector('.stage-card .card-value').textContent = opp.currentStageName;
        document.querySelector('.stage-card .card-desc').textContent = 
            `阶段 ${opp.currentStage}/12 · 进度 ${opp.progress}%`;
        
        // 更新预计金额卡片
        document.querySelector('.amount-card .card-value').textContent = 
            `¥${opp.expectedAmount.toLocaleString()}`;
        
        // 更新预计成交卡片
        document.querySelector('.date-card .card-value').textContent = opp.expectedCloseDate;
        const daysLeft = this.calculateDaysLeft(opp.expectedCloseDate);
        document.querySelector('.date-card .card-desc').textContent = 
            `距离还有 ${daysLeft} 天`;
    }

    updateSidebarInfo() {
        const opp = this.currentOpportunity;
        
        // 更新客户信息
        document.querySelector('.customer-card .customer-name').textContent = opp.customer.name;
        document.querySelector('.customer-card .customer-phone').textContent = opp.customer.phone;
        
        // 更新顾问信息
        document.querySelector('.consultant-card .consultant-name').textContent = opp.consultant.name;
        
        // 更新机会信息
        document.querySelector('.opportunity-info-card .detail-item:nth-child(1) .detail-value')
            .textContent = opp.source;
        document.querySelector('.opportunity-info-card .detail-item:nth-child(2) .detail-value')
            .textContent = opp.type;
    }

    calculateDaysLeft(dateStr) {
        const targetDate = new Date(dateStr);
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        targetDate.setHours(0, 0, 0, 0);
        
        const diffTime = targetDate - today;
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        
        return diffDays;
    }

    loadFollowupHistory() {
        // 模拟加载跟进历史数据
        this.followupHistory = this.getMockFollowupHistory();
        this.renderFollowupHistory();
    }

    getMockFollowupHistory() {
        return [
            {
                id: 1,
                date: '2025-01-21',
                time: '15:30',
                method: '电话沟通',
                duration: '25分钟',
                title: '电话沟通 - 价格协商',
                content: '与李女士详细讨论了云南7日游的价格构成，客户对酒店档次和餐饮标准比较关注。经过说明，客户对15800元的价格基本认可，但希望能有一些小的优惠。',
                tags: ['意向增强', '价格敏感'],
                result: {
                    feedback: '对方案整体满意，希望能优惠200-300元',
                    solution: '提供生日优惠200元，总价15600元',
                    nextPlan: '明天上午再次联系确认最终决定'
                },
                consultant: '张顾问'
            },
            {
                id: 2,
                date: '2025-01-20',
                time: '10:15',
                method: '微信交流',
                title: '微信发送方案 - 详细行程',
                content: '通过微信发送了详细的云南7日游行程方案，包含景点介绍、酒店图片、餐饮安排等。客户表示需要和老伴商量一下。',
                tags: ['需要商量', '方案认可'],
                result: {
                    feedback: '方案很详细，需要和老伴商量决定',
                    nextPlan: '给客户1天时间考虑，明天跟进'
                },
                consultant: '张顾问'
            }
        ];
    }

    renderFollowupHistory() {
        const timeline = document.querySelector('.followup-timeline');
        if (!timeline) return;
        
        let html = '';
        this.followupHistory.forEach(item => {
            html += this.generateFollowupItem(item);
        });
        
        timeline.innerHTML = html;
    }

    generateFollowupItem(item) {
        const tagsHtml = item.tags?.map(tag => 
            `<span class="tag tag-${this.getTagType(tag)}">${tag}</span>`
        ).join('') || '';
        
        const resultHtml = item.result ? `
            <div class="followup-result">
                ${item.result.feedback ? `<div class="result-item"><strong>客户反馈：</strong>${item.result.feedback}</div>` : ''}
                ${item.result.solution ? `<div class="result-item"><strong>解决方案：</strong>${item.result.solution}</div>` : ''}
                ${item.result.nextPlan ? `<div class="result-item"><strong>下次计划：</strong>${item.result.nextPlan}</div>` : ''}
            </div>
        ` : '';
        
        return `
            <div class="followup-item" data-followup-id="${item.id}">
                <div class="followup-time">
                    <div class="time-dot"></div>
                    <div class="time-info">
                        <div class="date">${item.date}</div>
                        <div class="time">${item.time}</div>
                    </div>
                </div>
                <div class="followup-content">
                    <div class="followup-header">
                        <div class="followup-title">${item.title}</div>
                        <div class="followup-meta">
                            <span class="method">${item.method}</span>
                            ${item.duration ? `<span class="duration">${item.duration}</span>` : ''}
                        </div>
                    </div>
                    <div class="followup-details">
                        <p>${item.content}</p>
                        <div class="followup-tags">${tagsHtml}</div>
                    </div>
                    ${resultHtml}
                    <div class="followup-footer">
                        <span class="consultant">${item.consultant}</span>
                        <div class="followup-actions">
                            <button class="action-btn" title="编辑">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="action-btn" title="删除">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    getTagType(tag) {
        const positiveKeywords = ['意向增强', '方案认可', '预算充足', '需求明确'];
        const neutralKeywords = ['需要商量', '价格敏感'];
        
        if (positiveKeywords.some(keyword => tag.includes(keyword))) {
            return 'positive';
        } else if (neutralKeywords.some(keyword => tag.includes(keyword))) {
            return 'neutral';
        }
        return 'info';
    }

    updateNextFollowupCard(data) {
        if (!data.nextFollowupTime) return;
        
        const card = document.querySelector('.next-followup-card .next-followup');
        if (!card) return;
        
        const date = new Date(data.nextFollowupTime);
        const dateStr = date.toLocaleDateString('zh-CN');
        const timeStr = date.toLocaleTimeString('zh-CN', {
            hour: '2-digit',
            minute: '2-digit'
        });
        
        card.querySelector('.followup-date').textContent = dateStr;
        card.querySelector('.followup-time').textContent = timeStr;
        
        if (data.nextFollowupGoal) {
            card.querySelector('.plan-title').textContent = data.nextFollowupGoal;
        }
    }

    // ==================== 组件初始化 ====================
    initializeComponents() {
        // 初始化其他组件
        this.initTooltips();
        this.initAnimations();
    }

    initTooltips() {
        // 初始化工具提示
        const tooltipElements = document.querySelectorAll('[title]');
        tooltipElements.forEach(element => {
            // 简单的工具提示实现
            element.addEventListener('mouseenter', (e) => {
                this.showTooltip(e.target, e.target.getAttribute('title'));
            });
            
            element.addEventListener('mouseleave', () => {
                this.hideTooltip();
            });
        });
    }

    initAnimations() {
        // 初始化页面动画
        const animatedElements = document.querySelectorAll('.overview-card, .info-card');
        
        // 使用 Intersection Observer 实现滚动动画
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.style.animationDelay = 
                        `${Array.from(animatedElements).indexOf(entry.target) * 100}ms`;
                    entry.target.classList.add('animate-in');
                }
            });
        });
        
        animatedElements.forEach(el => observer.observe(el));
    }

    // ==================== 工具方法 ====================
    showNotification(message, type = 'info') {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.innerHTML = `
            <div class="notification-content">
                <i class="fas fa-${this.getNotificationIcon(type)}"></i>
                <span>${message}</span>
            </div>
        `;
        
        // 添加样式
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: ${this.getNotificationColor(type)};
            color: white;
            padding: 12px 20px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            z-index: 10000;
            transform: translateX(100%);
            transition: transform 0.3s ease;
        `;
        
        document.body.appendChild(notification);
        
        // 显示动画
        setTimeout(() => {
            notification.style.transform = 'translateX(0)';
        }, 10);
        
        // 自动隐藏
        setTimeout(() => {
            notification.style.transform = 'translateX(100%)';
            setTimeout(() => {
                if (document.body.contains(notification)) {
                    document.body.removeChild(notification);
                }
            }, 300);
        }, 3000);
    }

    getNotificationIcon(type) {
        const icons = {
            success: 'check-circle',
            error: 'exclamation-circle',
            warning: 'exclamation-triangle',
            info: 'info-circle'
        };
        return icons[type] || 'info-circle';
    }

    getNotificationColor(type) {
        const colors = {
            success: '#30d158',
            error: '#ff3b30',
            warning: '#ff9500',
            info: '#007AFF'
        };
        return colors[type] || '#007AFF';
    }

    showTooltip(element, text) {
        this.hideTooltip();
        
        const tooltip = document.createElement('div');
        tooltip.className = 'tooltip';
        tooltip.textContent = text;
        tooltip.style.cssText = `
            position: absolute;
            background: #333;
            color: white;
            padding: 6px 10px;
            border-radius: 4px;
            font-size: 12px;
            white-space: nowrap;
            z-index: 10001;
            opacity: 0;
            transition: opacity 0.3s ease;
        `;
        
        document.body.appendChild(tooltip);
        
        const rect = element.getBoundingClientRect();
        tooltip.style.top = `${rect.top - tooltip.offsetHeight - 5}px`;
        tooltip.style.left = `${rect.left + (rect.width - tooltip.offsetWidth) / 2}px`;
        
        setTimeout(() => {
            tooltip.style.opacity = '1';
        }, 10);
        
        this.currentTooltip = tooltip;
    }

    hideTooltip() {
        if (this.currentTooltip) {
            this.currentTooltip.style.opacity = '0';
            setTimeout(() => {
                if (document.body.contains(this.currentTooltip)) {
                    document.body.removeChild(this.currentTooltip);
                }
                this.currentTooltip = null;
            }, 300);
        }
    }
}

// ==================== 全局函数 ====================
function closeFollowupModal() {
    window.opportunityDetail.closeFollowupModal();
}

function saveFollowup() {
    window.opportunityDetail.saveFollowup();
}

// ==================== 初始化 ====================
document.addEventListener('DOMContentLoaded', () => {
    window.opportunityDetail = new OpportunityDetail();
});